<template lang="pug">
.cp-custom-component
  .tree-wrap
    .tree-title
      div.tree-th(style="width: 270px") 名称
      div.tree-th(style="width: 88px") 分类码位数
      div.tree-th(style="width: 76px") 分类码值
      div.tree-th(style="width: 76px") 序号位数
      div.tree-th(style="width: 100px") 序号起始值
      div.tree-th(style="width: 100px") 序号截止值
      div.tree-th(style="width: 120px") 预览
      div.tree-th(style="width: 70px") 操作
    el-tree.tree-content(
      :data="treeData"
      ref="tree"
      node-key="id"
      v-loading="loading"
      default-expand-all,
      :expand-on-click-node="!isEdit")
      .custom-tree(slot-scope="{ node, data }")
        .tree-td.name(:style="calcWidth(data)", :class="{ 'border': !isEdit }")
          span.td-text(v-show="!isEdit || !data.level") {{ data.name }}
          el-input(v-show="isEdit && data.level", v-model="data.name")
        .tree-td.ordinal(style="width: 88px", :class="{ 'border': !isEdit }")
          span.td-text(v-show="!isEdit || !data.level") {{ data.ordinal }}
          el-input(v-show="isEdit && data.level", v-model="data.ordinal")
        .tree-td.prefix(style="width: 76px", :class="{ 'border': !isEdit }")
          span.td-text(v-show="!isEdit || !data.level") {{ data.prefix }}
          el-input(v-show="isEdit && data.level", v-model="data.prefix")
        .tree-td.snDigits(style="width: 76px", :class="{ 'border': !isEdit }")
          span.td-text(v-show="!isEdit || !data.level") {{ data.snDigits }}
          el-input(v-show="isEdit && data.level", v-model="data.snDigits")
        .tree-td.snBeginning(style="width: 100px", :class="{ 'border': !isEdit }")
          span.td-text(v-show="!isEdit || !data.level") {{ data.snBeginning }}
          el-input(v-show="isEdit && data.level", v-model="data.snBeginning")
        .tree-td.snEnding(style="width: 100px", :class="{ 'border': !isEdit }")
          span.td-text(v-show="!isEdit || !data.level") {{ data.snEnding }}
          el-input(v-show="isEdit && data.level", v-model="data.snEnding")
        .tree-td.preview.border(style="width: 120px", :class="{none: !data.level && isEdit}")
          el-tooltip(placement="top", :content="previewText(data)", :disabled="previewText(data).length < 12")
            span.td-text {{ previewText(data) }}
        .tree-td.action(style="width: 70px")
          span.td-text(v-show="isEdit")
            i.el-icon-plus.icon-act(@click="() => addNode(data)")
            i.el-icon-delete.icon-act(v-show="data.level", @click="() => removeNode(node, data)")
  .button-wrap
    el-button(type="primary", icon="el-icon-edit", @click="edit", v-show="!isEdit") 编辑
    el-button(@click="cancelEdit", v-show="isEdit") 取消
    el-button(type="primary", @click="submitEdit", v-show="isEdit") 确定
</template>

<script>
import ConfigApi from '@/api/config';

export default {
  name: 'customTypeTable',
  data() {
    return {
      isEdit: false,
      loading: true,
      treeData: [
        { id: '1', name: '根节点', parent: null, children: [], level: 0 }
      ]
    };
  },
  created() {
    // 缓存数据
    this.dataCache = [];
    // 文本缓存
    this.cache = {};
  },
  mounted() {
    this.loadSuppyChain();
  },
  methods: {
    loadSuppyChain() {
      ConfigApi.getDataSupplyChainDetail().then((res) => {
        if (res.status === 0) {
          this.treeData = res.obj;
        } else {
          this.$message.error(res.comment || '获取详情失败');
        }
        this.loading = false;
      }).catch((error) => {
        this.loading = false;
        console.log(JSON.stringify(error));
      });
    },
    // 获取id文本
    getIdText(id) {
      if (this.$refs.tree) {
        return this.$refs.tree.getNode(id);
      }
    },
    // 获取父级的文本
    getParentText(data, id) {
      if (data.parent) {
        const pnode = this.getIdText(data.parent);
        if (pnode) {
          this.cache[id].push(pnode.data.prefix);
          this.getParentText(pnode.data, id);
        }
      }
    },
    // 预览文本
    previewText(data) {
      this.cache[data.id] = [];
      this.getParentText(data, data.id);
      const pStr = this.cache[data.id].reverse().join('');
      let str = '';
      if (data.snDigits) {
        for (let i = 0; i < parseInt(data.snDigits, 10); i++) {
          str += 'X';
        }
      }
      const preview = `${pStr}${data.prefix || ''}${str}`;
      this.$set(data, 'preview', preview);
      return preview;
    },
    // 计算名称偏移
    calcWidth(data) {
      const width = 270 - 24;
      const len = (data.level) * 18;
      return {
        width: `${width - len}px`
      };
    },
    // 添加节点
    addNode(data) {
      let id = '';
      const level = data.level + 1;
      let len = 0;
      if (data.children && data.children.length) {
        len = data.children.length;
      }
      if (len > 0) {
        const last = data.children[len - 1].id;
        const arr = last.split('-');
        const prev = arr[arr.length - 1];
        id = `${data.id}-${Number(prev) + 1}`;
      } else {
        id = `${data.id}-1`;
      }
      const newChild = { id, level, parent: data.id, children: [] };
      if (!data.children) {
        this.$set(data, 'children', []);
      }
      data.children.push(newChild);
    },
    // 删除节点
    removeNode(node, data) {
      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d.id === data.id);
      children.splice(index, 1);
    },
    edit() {
      this.dataCache = JSON.parse(JSON.stringify(this.treeData));
      this.isEdit = true;
    },
    // 校验数据
    volidData(data) {
      if (data.children && data.children.length) {
        data.children.forEach((item) => {
          if (!item.ordinal) {
            this.$message.error('分类码位数不能为空');
            this.hasEmpty = true;
            return false;
          }
          if (!item.prefix) {
            this.$message.error('分类码值不能为空');
            this.hasEmpty = true;
            return false;
          }
          if (item.prefix.length !== parseInt(item.ordinal, 10)) {
            this.$message.error('分类码位数与分类码值不一致');
            this.hasEmpty = true;
            return false;
          }
          this.volidData(item);
        });
      }
    },
    // 保存
    submitEdit() {
      this.hasEmpty = false;
      this.volidData(this.treeData[0]);
      if (this.hasEmpty) {
        return false;
      }
      this.loading = true;
      const params = this.treeData;
      ConfigApi.updateDataSupplyChainDetail(params).then((res) => {
        if (res.status === 0) {
          this.loading = false;
          this.isEdit = false;
          this.$message({ message: '保存成功', type: 'success' });
        } else {
          this.$message.error(res.comment || '保存失败');
          this.loading = false;
        }
      }).catch((error) => {
        this.loading = false;
        console.log(JSON.stringify(error));
        this.$message.error('网络不给力，请稍后再试');
      });
    },
    // 取消
    cancelEdit() {
      this.treeData = this.dataCache;
      this.isEdit = false;
    }
  },
};
</script>

<style lang="sass">
$HEIGHT: 40px
$BORDERCOLOR: #dcdfe6
.cp-custom-component
  height: 100%
  max-width: 914px
  background: #fff
  overflow-y: auto
  border: 1px solid $BORDERCOLOR
  .button-wrap
    min-width: 900px
    text-align: center
    height: 50px
    line-height: 50px
  .tree-wrap
    min-width: 900px
    height: calc(100% - 50px)
    border-bottom: 1px solid $BORDERCOLOR
    .tree-title
      width: 100%
      height: 38px
      line-height: 38px
      font-weight: 500
      border-bottom: 1px solid $BORDERCOLOR
      .tree-th
        display: inline-block
        text-align: center
        font-size: 12px
        line-height: 38px
        color: #909399
        font-weight: 700
        border-right: 1px solid $BORDERCOLOR
        &:last-child
          border-right: none
    .tree-content
      height: calc(100% - 38px)
      overflow-y: auto
      overflow-x: hidden
    .el-tree-node__content
      height: $HEIGHT
    .el-tree-node:focus>.el-tree-node__content, .el-tree-node__content:hover
      background-color: transparent
    .custom-tree
      flex: 1
      display: flex
      align-items: center
      font-size: 12px
      height: $HEIGHT
      line-height: $HEIGHT
      .tree-td
        width: 92px
        height: 32px
        line-height: 32px
        &.border
          border: 1px solid $BORDERCOLOR
          border-left: none;
        &.border.name
          border-left: 1px solid $BORDERCOLOR
        &.action
          border: none
        &.preview
          white-space: nowrap
          word-break: break-all
          overflow: hidden
          text-overflow: ellipsis
          &.none
            border: none
        .td-text
          line-height: 32px
          padding: 0px 15px
        .el-input__inner
          font-size: 12px
          border-radius: 0
          border-color: $BORDERCOLOR
          border-left: none
          &:hover, &:focus
            border-color: $BORDERCOLOR
        &.name
          .el-input__inner
            border-left: 1px solid $BORDERCOLOR
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: 3px
    margin-right: 3px
    &:hover
      color: #5D9BFB
</style>
